package com.itheima;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 测试写入表格
 */
public class WriteXLSX {
    public static void main(String[] args) throws IOException {

        List<Student> list = new ArrayList<>();
        list.add(new Student("张三", 23, "001", "重庆"));
        list.add(new Student("李四", 24, "002", "长沙"));
        list.add(new Student("王麻子", 25, "003", "成都"));
        list.add(new Student("赵六", 26, "004", "北京"));

        XSSFWorkbook workbook = new XSSFWorkbook();

        XSSFSheet sheet = workbook.createSheet("表格1");

        XSSFRow row1 = sheet.createRow(0);
        row1.createCell(0, Cell.CELL_TYPE_STRING).setCellValue("姓名");
        row1.createCell(1, Cell.CELL_TYPE_STRING).setCellValue("年龄");
        row1.createCell(2, Cell.CELL_TYPE_STRING).setCellValue("学号");
        row1.createCell(3, Cell.CELL_TYPE_STRING).setCellValue("住址");

        for (int i = 1; i <= list.size(); i++) {
            XSSFRow row = sheet.createRow(i);
            Student student = list.get(i - 1);
            row.createCell(0, Cell.CELL_TYPE_STRING).setCellValue(student.getName());
            row.createCell(1, Cell.CELL_TYPE_STRING).setCellValue(student.getAge());
            row.createCell(2, Cell.CELL_TYPE_STRING).setCellValue(student.getId());
            row.createCell(3, Cell.CELL_TYPE_STRING).setCellValue(student.getAddress());
        }

        FileOutputStream fos = new FileOutputStream("src\\main\\resources\\write.xlsx");

        workbook.write(fos);
        fos.flush();

        fos.close();
        System.out.println("resources目录下的write.xlsx文件生成成功,查看后删除,以免影响下次测试");

    }
}
